import store from '@/store'
import { parseTime } from '@/util'

export class TimedError extends Error {
  create_at = 0
  err = null
  constructor(error) {
    super(error.message)
    this.err = error
    this.create_at = (new Date()).getTime()
  }
}

const today = new Date()

function buildTimeText(time) {
  time = new Date(time)
  if (today.getFullYear() !== time.getFullYear()) {
    return parseTime(time, '{y}年{m}月{d}日 {h}:{i}:{s}')
  } else if (!((today.getMonth() === time.getMonth()) && (today.getDate() === time.getDate()))) {
    return parseTime(time, '{m}月{d}日 {h}:{i}:{s}')
  } else {
    return parseTime(time, '{h}:{i}:{s}')
  }
}

function appendInfo(item) {
  const result = { ...item }
  result.to = store.getters.getUserById(result.to_id)
  result.from = store.getters.getUserById(result.from_id)
  result.is_me = result.from_id === store.getters.currentUserId
  return result
}

export function buildItemList(input) {
  if (input.length <= 0) return input

  const result = []
  let lastTime = 0
  let id = 1

  const pushTime = time => {
    result.push({
      type: 'time',
      id: `time_${id++}`,
      item: buildTimeText(time)
    })
  }

  const pushError = err => {
    result.push({
      type: 'error',
      id: `error_${id++}`,
      item: err
    })
  }

  const pushMessage = message => {
    result.push({
      type: 'message',
      id: `message_${message.id}`,
      item: message
    })
  }

  for (const item of input) {
    if (item instanceof Error) {
      pushError(item)
    } else {
      if (item.create_at - lastTime > 5 * 60 * 1000) {
        lastTime = item.create_at
        pushTime(lastTime)
      }
      pushMessage(appendInfo(item))
    }
  }

  return result
}
